<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css"/>




  <link href="//fonts.googleapis.com/css?family=Lato:300,400,700,400italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">



<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="crawl,python," />





  <link rel="alternate" href="/atom.xml" title="追背影的熊孩子" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.0" />






<meta name="description" content="&amp;#x524D;&amp;#x8A00;&amp;#xFF1A;
&amp;#x4E3A;&amp;#x4E86;&amp;#x5E2E;&amp;#x90FD;&amp;#x54E5;&amp;#x89E3;&amp;#x51B3;python &amp;#x722C;&amp;#x866B;&amp;#x65F6;&amp;#x9047;&amp;#x5230;&amp;#x7684;&amp;#x95EE;&amp;#x9898;&amp;#xFF0C;&amp;#x53C8;&amp;#x590D;&amp;#x4E60;&amp;#x4E86;&amp;#x4E0B;">
<meta property="og:type" content="article">
<meta property="og:title" content="python 爬取知乎">
<meta property="og:url" content="http://b.fengbl.cn/2015/12/06/Python_crawl/index.html">
<meta property="og:site_name" content="追背影的熊孩子">
<meta property="og:description" content="&amp;#x524D;&amp;#x8A00;&amp;#xFF1A;
&amp;#x4E3A;&amp;#x4E86;&amp;#x5E2E;&amp;#x90FD;&amp;#x54E5;&amp;#x89E3;&amp;#x51B3;python &amp;#x722C;&amp;#x866B;&amp;#x65F6;&amp;#x9047;&amp;#x5230;&amp;#x7684;&amp;#x95EE;&amp;#x9898;&amp;#xFF0C;&amp;#x53C8;&amp;#x590D;&amp;#x4E60;&amp;#x4E86;&amp;#x4E0B;">
<meta property="og:updated_time" content="2016-01-15T12:29:14.471Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="python 爬取知乎">
<meta name="twitter:description" content="&amp;#x524D;&amp;#x8A00;&amp;#xFF1A;
&amp;#x4E3A;&amp;#x4E86;&amp;#x5E2E;&amp;#x90FD;&amp;#x54E5;&amp;#x89E3;&amp;#x51B3;python &amp;#x722C;&amp;#x866B;&amp;#x65F6;&amp;#x9047;&amp;#x5230;&amp;#x7684;&amp;#x95EE;&amp;#x9898;&amp;#xFF0C;&amp;#x53C8;&amp;#x590D;&amp;#x4E60;&amp;#x4E86;&amp;#x4E0B;">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: '[object Object]',
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>

  <title> python 爬取知乎 | 追背影的熊孩子 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  



  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?132dfd4f90476131a6139e7cd32e426b";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">追背影的熊孩子</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">Notes & Stories</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu menu-left">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-home fa-fw"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-th fa-fw"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-archive fa-fw"></i> <br />
            
            归档
          </a>
        </li>
      

      
      
      
        <li class="menu-item menu-item-search">
          <a href="#" class="st-search-show-outputs">
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <form class="site-search-form">
  <input type="text" id="st-search-input" class="st-search-input st-default-search-input" />
</form>

<script type="text/javascript">
  (function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){
    (w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t);
    e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e);
  })(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st');

  _st('install', 'T4o6Q_jTr-CKSx9X79oD','2.0.0');
</script>



    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                python 爬取知乎
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2015-12-06T22:36:00+08:00" content="2015-12-06">
              2015-12-06
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/python/" itemprop="url" rel="index">
                    <span itemprop="name">python</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2015/12/06/Python_crawl/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2015/12/06/Python_crawl/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="&#x524D;&#x8A00;">&#x524D;&#x8A00;&#xFF1A;</h3><blockquote>
<p>&#x4E3A;&#x4E86;&#x5E2E;&#x90FD;&#x54E5;&#x89E3;&#x51B3;python &#x722C;&#x866B;&#x65F6;&#x9047;&#x5230;&#x7684;&#x95EE;&#x9898;&#xFF0C;&#x53C8;&#x590D;&#x4E60;&#x4E86;&#x4E0B;python&#xFF0C;&#x5E76;&#x4E14;&#x5C1D;&#x8BD5;&#x722C;&#x53D6;&#x4E86;&#x77E5;&#x4E4E;&#x9875;&#x9762;&#x3002; &#x5728;&#x8FD9;&#x91CC;&#x8BB0;&#x4E0B;&#x9047;&#x5230;&#x7684;&#x95EE;&#x9898;&#x3002;</p>
</blockquote>
<hr>
<h3 id="&#x8E29;&#x70B9;">&#x8E29;&#x70B9;</h3><p>&#x6B63;&#x5E38;&#x767B;&#x5F55;&#x4E00;&#x6B21; <a href="http://www.zhihu.com" target="_blank" rel="external">&#x77E5;&#x4E4E;</a> &#x5E76;&#x5728;Fiddler&#x9762;&#x677F;&#x67E5;&#x770B;&#x8BE6;&#x7EC6;&#x4FE1;&#x606F;</p>
<h4 id="fiddler&#x67E5;&#x770B;header">Fiddler&#x67E5;&#x770B;Header</h4><p>&#x83B7;&#x53D6;&#x8BF7;&#x6C42;&#x5185;&#x5BB9;</p>
<pre><code><span class="request">POST <span class="string">http://www.zhihu.com/login/email</span> HTTP/1.1</span>
<span class="attribute">Content-Type</span>: <span class="string">application/x-www-form-urlencoded; charset=UTF-8</span>
<span class="attribute">Accept</span>: <span class="string">*/*</span>
<span class="attribute">X-Requested-With</span>: <span class="string">XMLHttpRequest</span>
<span class="attribute">Referer</span>: <span class="string">http://www.zhihu.com/#signin</span>
<span class="attribute">Accept-Language</span>: <span class="string">zh-CN</span>
<span class="attribute">Accept-Encoding</span>: <span class="string">gzip, deflate</span>
<span class="attribute">User-Agent</span>: <span class="string">Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)</span>
<span class="attribute">Content-Length</span>: <span class="string">93</span>
<span class="attribute">Host</span>: <span class="string">www.zhihu.com</span>

<span class="bash">_xsrf=<span class="number">7150</span>c8e5d9ef17589681c80c276611ea&amp;password=<span class="built_in">test</span>&amp;captcha=<span class="number">5</span>SAK&amp;remember_me=<span class="literal">true</span>&amp;email=<span class="built_in">test</span></span>
</code></pre><h4 id="&#x5168;&#x5C40;&#x5171;&#x7528;cookie">&#x5168;&#x5C40;&#x5171;&#x7528;cookie</h4><pre><code>self<span class="class">.cookie</span> = cookielib.<span class="function"><span class="title">LWPCookieJar</span><span class="params">()</span></span>
#&#x8BBE;&#x7F6E;cookie&#x5904;&#x7406;&#x5668;
self<span class="class">.cookieHandler</span> = urllib2.<span class="function"><span class="title">HTTPCookieProcessor</span><span class="params">(self.cookie)</span></span>
#&#x8BBE;&#x7F6E;&#x767B;&#x5F55;&#x65F6;&#x7528;&#x5230;&#x7684;opener
self<span class="class">.opener</span> = urllib2.<span class="function"><span class="title">build_opener</span><span class="params">(self.cookieHandler,urllib2.HTTPHandler)</span></span>
urllib2.<span class="function"><span class="title">install_opener</span><span class="params">(self.opener)</span></span>
</code></pre><h3 id="&#x6A21;&#x62DF;&#x8BF7;&#x6C42;">&#x6A21;&#x62DF;&#x8BF7;&#x6C42;</h3><pre><code><span class="attribute">content</span> = urllib2.<span class="function"><span class="title">urlopen</span><span class="params">(<span class="string">&apos;http://www.zhihu.com/&apos;</span>)</span></span>
</code></pre><h4 id="&#x53D6;&#x51FA;&#x9690;&#x85CF;&#x5B57;&#x6BB5;xsrt">&#x53D6;&#x51FA;&#x9690;&#x85CF;&#x5B57;&#x6BB5;xsrt</h4><pre><code>xsrf = re.search(<span class="string">r&apos;(?&lt;=name=&quot;_xsrf&quot; value=&quot;)[^&quot;]*(?=&quot;/&gt;)&apos;</span>, content).group(<span class="number">0</span>);
</code></pre><h4 id="&#x8BF7;&#x6C42;&#x9A8C;&#x8BC1;&#x7801;">&#x8BF7;&#x6C42;&#x9A8C;&#x8BC1;&#x7801;</h4><pre><code><span class="attribute">content</span> = urllib2.<span class="function"><span class="title">urlopen</span><span class="params">(<span class="string">&apos;http://www.zhihu.com/&apos;</span>)</span></span>
</code></pre><h4 id="&#x6784;&#x9020;post&#x6570;&#x636E;">&#x6784;&#x9020;post&#x6570;&#x636E;</h4><pre><code><span class="setting">post_data = <span class="value">{<span class="string">&apos;_xsrf&apos;</span>: xsrf, <span class="string">&apos;email&apos;</span>: <span class="string">&apos;494046250@qq.com&apos;</span>,<span class="string">&apos;password&apos;</span>: <span class="string">&apos;8925159qz&apos;</span>, <span class="string">&apos;remember_me&apos;</span>: <span class="keyword">True</span>,<span class="string">&apos;captcha&apos;</span>: captcha}</span></span>
</code></pre><h4 id="&#x5C1D;&#x8BD5;&#x767B;&#x9646;">&#x5C1D;&#x8BD5;&#x767B;&#x9646;</h4><h4 id="unzip&#x767B;&#x9646;&#x7ED3;&#x679C;">unzip&#x767B;&#x9646;&#x7ED3;&#x679C;</h4><pre><code><span class="keyword">if</span> decode and <span class="string">&quot;gzip&quot;</span> <span class="keyword">in</span> decode:
        try:
            <span class="attribute">content</span> = zlib.<span class="function"><span class="title">decompress</span><span class="params">(content, <span class="number">16</span> + zlib.MAX_WBITS)</span></span>
        except zlib<span class="class">.error</span> as error:
            Debug<span class="class">.logger</span><span class="class">.info</span>(<span class="string">&apos;&#x89E3;&#x538B;&#x51FA;&#x9519;&apos;</span>)
            Debug<span class="class">.logger</span><span class="class">.info</span>(<span class="string">&apos;&#x9519;&#x8BEF;&#x4FE1;&#x606F;:{}&apos;</span>.<span class="function"><span class="title">format</span><span class="params">(error)</span></span>)
</code></pre><h4 id="&#x4FDD;&#x5B58;cookie&#x65B9;&#x4FBF;&#x4E0B;&#x6B21;&#x767B;&#x9646;">&#x4FDD;&#x5B58;cookie&#x65B9;&#x4FBF;&#x4E0B;&#x6B21;&#x767B;&#x9646;</h4><pre><code>zhihu_cookie = os.path.abspath(<span class="string">&apos;./&apos;</span>) + <span class="string">&apos;/zhihu_cookie_new_try.txt&apos;</span>
<span class="comment">#&#x4FDD;&#x5B58;cookie</span>
<span class="keyword">self</span>.cookie.save(zhihu_cookie);
<span class="comment">#&#x4F7F;&#x7528;cookie</span>
<span class="keyword">self</span>.cookie.load(zhihu_cookie)
</code></pre>
      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/crawl/" rel="tag">#crawl</a>
          
            <a href="/tags/python/" rel="tag">#python</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2015/12/06/php-summary/" rel="next" title="PHP知识点">
                <i class="fa fa-chevron-left"></i> PHP知识点
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2015/12/10/css-study/" rel="prev" title="前端常用">
                前端常用 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>




    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2015/12/06/Python_crawl/"
           data-title="python 爬取知乎" data-url="http://b.fengbl.cn/2015/12/06/Python_crawl/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://ww4.sinaimg.cn/large/c048f998jw1ey8qmhh0pjj20g40ebjs7.jpg"
               alt="Fengit" />
          <p class="site-author-name" itemprop="name">Fengit</p>
          <p class="site-description motion-element" itemprop="description">在成为最厉害最厉害最厉害的道路上.</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">19</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          <div class="site-state-item site-state-categories">
            <a href="/categories">
              <span class="site-state-item-count">9</span>
              <span class="site-state-item-name">分类</span>
              </a>
          </div>

          <div class="site-state-item site-state-tags">
          <a href="/tags">
              <span class="site-state-item-count">27</span>
              <span class="site-state-item-name">标签</span>

          </a>
          </div>

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/hmilyfyj" target="_blank">
                  
                    <i class="fa fa-github"></i> GitHub
                  
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.weibo.com/3226007960" target="_blank">
                  
                    <i class="fa fa-weibo"></i> Weibo
                  
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.zhihu.com/people/feng-ying-jie" target="_blank">
                  
                    <i class="fa fa-globe"></i> zhihu
                  
                </a>
              </span>
            
          
        </div>

        
        

        <div class="links-of-author motion-element">
          
        </div>

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc-indicator-top post-toc-indicator">
            <i class="fa fa-angle-double-up"></i>
          </div>
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#踩点"><span class="nav-number">2.</span> <span class="nav-text">踩点</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#fiddler查看header"><span class="nav-number">2.1.</span> <span class="nav-text">Fiddler查看Header</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#全局共用cookie"><span class="nav-number">2.2.</span> <span class="nav-text">全局共用cookie</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#模拟请求"><span class="nav-number">3.</span> <span class="nav-text">模拟请求</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#取出隐藏字段xsrt"><span class="nav-number">3.1.</span> <span class="nav-text">取出隐藏字段xsrt</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#请求验证码"><span class="nav-number">3.2.</span> <span class="nav-text">请求验证码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#构造post数据"><span class="nav-number">3.3.</span> <span class="nav-text">构造post数据</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#尝试登陆"><span class="nav-number">3.4.</span> <span class="nav-text">尝试登陆</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#unzip登陆结果"><span class="nav-number">3.5.</span> <span class="nav-text">unzip登陆结果</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#保存cookie方便下次登陆"><span class="nav-number">3.6.</span> <span class="nav-text">保存cookie方便下次登陆</span></a></li></ol></li></ol></div>
            
          </div>
          <div class="post-toc-indicator-bottom post-toc-indicator">
            <i class="fa fa-angle-double-down"></i>
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="icon-next-heart fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Fengit</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="http://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>



      </div>
    </footer>

    <div class="back-to-top"></div>
  </div>

  


  



  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  <script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>

  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>

  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.0"></script>



  
  
<script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.0"></script>

<script type="text/javascript" id="sidebar.toc.highlight">
  $(document).ready(function () {
    var tocSelector = '.post-toc';
    var $tocSelector = $(tocSelector);
    var activeCurrentSelector = '.active-current';

    $tocSelector
      .on('activate.bs.scrollspy', function () {
        var $currentActiveElement = $(tocSelector + ' .active').last();

        removeCurrentActiveClass();
        $currentActiveElement.addClass('active-current');

        $tocSelector[0].scrollTop = $currentActiveElement.position().top;
      })
      .on('clear.bs.scrollspy', function () {
        removeCurrentActiveClass();
      });

    function removeCurrentActiveClass () {
      $(tocSelector + ' ' + activeCurrentSelector)
        .removeClass(activeCurrentSelector.substring(1));
    }

    function processTOC () {
      getTOCMaxHeight();
      toggleTOCOverflowIndicators();
    }

    function getTOCMaxHeight () {
      var height = $('.sidebar').height() -
                   $tocSelector.position().top -
                   $('.post-toc-indicator-bottom').height();

      $tocSelector.css('height', height);

      return height;
    }

    function toggleTOCOverflowIndicators () {
      tocOverflowIndicator(
        '.post-toc-indicator-top',
        $tocSelector.scrollTop() > 0 ? 'show' : 'hide'
      );

      tocOverflowIndicator(
        '.post-toc-indicator-bottom',
        $tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show'
      )
    }

    $(document).on('sidebar.motion.complete', function () {
      processTOC();
    });

    $('body').scrollspy({ target: tocSelector });
    $(window).on('resize', function () {
      if ( $('.sidebar').hasClass('sidebar-active') ) {
        processTOC();
      }
    });

    onScroll($tocSelector);

    function onScroll (element) {
      element.on('mousewheel DOMMouseScroll', function (event) {
          var oe = event.originalEvent;
          var delta = oe.wheelDelta || -oe.detail;

          this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
          event.preventDefault();

          toggleTOCOverflowIndicators();
      });
    }

    function tocOverflowIndicator (indicator, action) {
      var $indicator = $(indicator);
      var opacity = action === 'show' ? 1 : 0;
      $indicator.velocity ?
        $indicator.velocity('stop').velocity({
          opacity: opacity
        }, { duration: 100 }) :
        $indicator.stop().animate({
          opacity: opacity
        }, 100);
    }

  });
</script>

<script type="text/javascript" id="sidebar.nav">
  $(document).ready(function () {
    var html = $('html');
    var TAB_ANIMATE_DURATION = 200;
    var hasVelocity = $.isFunction(html.velocity);

    $('.sidebar-nav li').on('click', function () {
      var item = $(this);
      var activeTabClassName = 'sidebar-nav-active';
      var activePanelClassName = 'sidebar-panel-active';
      if (item.hasClass(activeTabClassName)) {
        return;
      }

      var currentTarget = $('.' + activePanelClassName);
      var target = $('.' + item.data('target'));

      hasVelocity ?
        currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () {
          target
            .velocity('stop')
            .velocity('transition.slideDownIn', TAB_ANIMATE_DURATION)
            .addClass(activePanelClassName);
        }) :
        currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () {
          currentTarget.hide();
          target
            .stop()
            .css({'opacity': 0, 'display': 'block'})
            .animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () {
              currentTarget.removeClass(activePanelClassName);
              target.addClass(activePanelClassName);
            });
        });

      item.siblings().removeClass(activeTabClassName);
      item.addClass(activeTabClassName);
    });

    $('.post-toc a').on('click', function (e) {
      e.preventDefault();
      var targetSelector = NexT.utils.escapeSelector(this.getAttribute('href'));
      var offset = $(targetSelector).offset().top;
      hasVelocity ?
        html.velocity('stop').velocity('scroll', {
          offset: offset  + 'px',
          mobileHA: false
        }) :
        $('html, body').stop().animate({
          scrollTop: offset
        }, 500);
    });

    // Expand sidebar on post detail page by default, when post has a toc.
    NexT.motion.middleWares.sidebar = function () {
      var $tocContent = $('.post-toc-content');

      if (CONFIG.sidebar === 'post') {
        if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) {
          NexT.utils.displaySidebar();
        }
      }
    };
  });
</script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.0"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"fenghexo"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      //ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.src = '/js/src/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
  






  
  

  

<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"1","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"slide":{"type":"slide","bdImg":"3","bdPos":"left","bdTop":"250"}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>


  

  <script type="text/javascript">

  $(document).ready(function(){
    var isMobile = navigator.userAgent.match(/iphone|android|phone|mobile|wap|netfront|x11|java|opera mobi|opera mini|ucweb|windows ce|symbian|symbianos|series|webos|sony|blackberry|dopod|nokia|samsung|palmsource|xda|pieplus|meizu|midp|cldc|motorola|foma|docomo|up.browser|up.link|blazer|helio|hosin|huawei|novarra|coolpad|webos|techfaith|palmsource|alcatel|amoi|ktouch|nexian|ericsson|philips|sagem|wellcom|bunjalloo|maui|smartphone|iemobile|spice|bird|zte-|longcos|pantech|gionee|portalmmm|jig browser|hiptop|benq|haier|^lct|320x320|240x320|176x220/i);
    isMobile = (isMobile != null);
  if (!isMobile) {
    $(function() {
        var $sidebar   = $("#sidebar"),
            $window    = $(window),
            $header    = $("#header-inner"),
            offset     = $sidebar.offset(),
            topPadding = 15;

        $window.scroll(function() {
            if ($window.scrollTop() > offset.top) {
              //console.log($window.scrollTop());
              //console.log(offset.top);
                $sidebar.stop().animate({
                    //marginTop: $window.scrollTop() - offset.top + topPadding
                    marginTop: $window.scrollTop()  + topPadding
                });
            } else {
                $sidebar.stop().animate({
                    marginTop: offset.top
                });
            }
        });

    });
    }
  });
  </script>

</body>
</html>
